<template>
<div class="wrapper">
              <v-head  @getContDiv="handerHead" ></v-head>
              <v-sidebar></v-sidebar>
              <div  :class="['content-box', showClass ? 'content-collapse' : '']">
                  <div class="content_wrapper">
                      <v-tags></v-tags>
                      <div class="container messageboard">
                              <!-- 查询区----start -->
                              <el-form :label-position="labelPosition" :label-width="labelWidth" :inline="true" ref="formSearch" :model="formSearch" class="demo-form-inline">
                                  <el-form-item label="任务名称" prop="task_name">
                                      <el-input v-model="formSearch.name" placeholder="任务名称"></el-input>
                                  </el-form-item>
                                  <el-form-item label="状态" prop="status">
                                      <el-select v-model="formSearch.status" placeholder="状态">
                                          <el-option label="完成" value=3></el-option>
                                          <el-option label="暂停" value=2></el-option>
                                          <el-option label="运行中" value=1></el-option>
                                          <el-option label="未开始" value=0></el-option>
                                      </el-select>
                                  </el-form-item>
                                  <el-form-item label="创建时间" prop="createtime">
                                      <el-date-picker
                                          v-model="formSearch.createtime"
                                          type="daterange"
                                          range-separator="至"
                                          start-placeholder="开始日期"
                                          end-placeholder="结束日期">
                                      </el-date-picker>
                                  </el-form-item>
                                  <el-form-item label=" " style="margin-left:50px;">
                                      <el-button type="primary" @click="onSearch">查询</el-button>
                                      <el-button type="warning" plain @click="onReset">重置</el-button>
                                  </el-form-item>
                              </el-form>
                              <!-- 查询区----end -->
                              <!-- 操作区----start -->
                              <el-row class="mgb15">
                                  <el-button size="small" round type="primary" @click="handleAdd">新增</el-button>
                              <!--    <el-button size="small" round type="danger" @click="deleteMany">批量删除</el-button>-->
                              </el-row>
                              <!-- 操作区----end -->
                              <!-- 表格---start -->
                              <el-table :data="tableData" v-loading="listLoading"  border stripe style="width: 100%" @selection-change="handleSelectionChange">
                                  <el-table-column prop="taskName" label="任务名称" width="140" align="center" sortable>
                                  </el-table-column>
                                  <el-table-column prop="crawldb" label="数据库地址" align="center" width="180">
                                  </el-table-column>
                                 <!-- <el-table-column prop="remark" label="备注" align="center" width="180">
                                  </el-table-column>-->
                                <el-table-column prop="status" label="状态" align="center" width="120" >
                                </el-table-column>
                                  <el-table-column prop="createTime" label="创建日期" :formatter="this.$common.timestampToTime" width="160" sortable>
                                  </el-table-column>
                                  <el-table-column label="操作" fixed="right" min-width="230">
                                      <template slot-scope="scope">
                                          <el-button size="mini" plain type="primary" @click="handleSeedList(scope.$index, scope.row)">种子配置</el-button>
                                          <el-button size="mini" plain type="small" @click="handleFilter(scope.$index, scope.row)">爬取配置</el-button>
                                          <el-button size="mini" plain type="group" @click="handleTask(scope.$index, scope.row)">任务配置</el-button>
                                          <el-button size="mini" plain type="info" @click="handleParse(scope.$index, scope.row)">提取配置</el-button>
                                        <el-button size="mini" plain type="success" @click="handleStart(scope.$index, scope.row)" v-if="scope.row.status=='未开始'||scope.row.status=='暂停'" >启用</el-button>
                                        <el-button size="mini" plain type="success" @click="handleStop(scope.$index, scope.row)" v-if="scope.row.status=='运行中'" >停用</el-button>
                                        <el-button size="mini" plain type="success" :disabled="true" v-if="scope.row.status=='完成'" >完成</el-button>

                                        <el-button size="mini" plain type="info" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
                                          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                          <el-button size="mini" plain type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                                      </template>
                                  </el-table-column>
                              </el-table>
                              <el-pagination background layout="total,sizes,prev, pager, next,jumper" :current-page="pageInfo.currentPage" :page-size="pageInfo.pageSize" :total="pageInfo.pageTotal" :page-sizes="[5, 10, 20, 50]" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                              </el-pagination>
                              <!-- 表格---end -->

                              <!-- 编辑弹框---start -->
                              <el-dialog  :title="formEditTitle" :visible.sync="dialogEdittVisible" width="700px" @close="closeDialog('formEdit')">
                                  <el-form :label-position="labelPosition" :label-width="labelWidth" :rules="rulesEdit" :disabled="formEditDisabled" :inline="true" ref="formEdit" :model="formEdit" class="demo-form-inline">
                                       <el-form-item label="任务名称" prop="taskName">
                                          <el-input v-model="formEdit.taskName" placeholder="请输入任务名称" ></el-input>
                                      </el-form-item>
                                      <el-form-item label="DB地址" prop="crawldb">
                                          <el-input v-model="formEdit.crawldb" placeholder="数据库地址"></el-input>
                                      </el-form-item>
                                      <el-form-item label="备注" prop="remark">
                                           <el-input  v-model="formEdit.remark" placeholder="备注" ></el-input>
                                      </el-form-item>
                                      <el-form-item label="运行状态" prop="status">
                                           <el-input  v-model="formEdit.status" placeholder="运行状态" disabled></el-input>
                                      </el-form-item>
                                      <el-form-item label="文件大小" prop="file_size">
                                          <el-input v-model="formEdit.file_size" placeholder="结果文件大小" disabled></el-input>
                                      </el-form-item>
                                      <el-form-item label="文件行数" prop="count_line">
                                           <el-input v-model="formEdit.count_line" placeholder="结果文件行数" disabled></el-input>
                                      </el-form-item>
                                      <el-form-item label="创建人" prop="creator">
                                           <el-input  v-model="formEdit.creator" placeholder="创建人" disabled ></el-input>
                                      </el-form-item>
                                      <el-form-item label="创建时间" prop="createTime" :formatter="this.$common.timestampToTime">
                                            <el-date-picker  v-model="formEdit.createTime" type="date"  @change="this.$common.getTime" format="yyyy-MM-dd HH:mm:ss" disabled>
                                            </el-date-picker>
                                      </el-form-item>
                                       <el-form-item label="更新时间" prop="updateTime" :formatter="this.$common.timestampToTime">
                                            <el-date-picker  v-model="formEdit.updateTime" type="date"  @change="this.$common.getTime" format="yyyy-MM-dd HH:mm:ss" disabled>
                                            </el-date-picker>
                                       </el-form-item>
                                      <el-input  v-model="formEdit.taskId" placeholder="taskId" style="display : none" ></el-input>
                                  </el-form>

                                  <div slot="footer" class="dialog-footer">
                                      <el-button @click="dialogEdittVisible = false">取 消</el-button>
                                      <el-button v-if="!formEditDisabled" type="primary" @click="handleSave">确 定</el-button>
                                  </div>
                              </el-dialog>

                              <!-- 编辑弹框---end -->
                          </div>

                      </div>
                      <v-footer></v-footer>
                  </div>

              </div>
          </div>

</template>

<style lang="scss">
.messageboard{
    //设置输入框的宽度
    .el-form-item__content {
        width: 220px;
    }
}
</style>

<script>
import apis from '../../apis/apis';
import vHead from '../common/Header.vue';
import vSidebar from '../common/Sidebar.vue';
import vTags from '../common/Tags.vue';
import vFooter from '../common/Footer.vue';
import bus from '../common/bus';
export default {
    name: 'messageboard',
    data() {
        return {
            showClass :false,
            listLoading : false,//
            pageInfo: { //分页
                currentPage: 1,
                pageSize: 5,
                pageTotal: 0
            },
            formSearch: { //表单查询
                name: '',
                status:'',
              createTime: ''
            },
            formEdit: { //表单编辑
                taskId:null,
                taskName: '',
                remark:'',
                createTime : ''
            },
             rulesEdit:  {
                name: [
                    { required: true, message: "请输入姓名", trigger: "blur" },
                    { min: 2, max: 4, message: "长度在 2 到 4 个字符", trigger: "blur" }
                ],
                sex: [{ required: true, message: "请选择性别", trigger: "change" }]
            },
            formEditTitle:'编辑',//新增，编辑和查看标题
            formEditDisabled:false,//编辑弹窗是否可编辑
            dialogEdittVisible: false,  //编辑弹框显示
            dialogType:'',//弹框类型：add,edit,show
            tableData: [],
            labelPosition: 'right', //lable对齐方式
            labelWidth: '80px', //lable宽度
            formLabelWidth: '120px',
            multipleSelection: [],
        };
    },
    components: {
              vHead, vSidebar, vTags, vFooter
          },
    created() {
                  bus.$on('collapse', msg => {
                      this.collapse = msg;
                  })

                  // 只有在标签页列表里的页面才使用keep-alive，即关闭标签之后就不保存到内存中了。
                  bus.$on('tags', msg => {
                      let arr = [];
                      for (let i = 0, len = msg.length; i < len; i++) {
                          msg[i].name && arr.push(msg[i].name);
                      }
                      this.tagsList = arr;
                  })
                setInterval(this.onSearch, 60000);
       },
    computed:{

    },
    filters: {

    },
    mounted(){
        this.onSearch();
    },
    methods: {
      handerHead() {
        this.showClass == true ? (this.showClass = false) : (this.showClass = true);
      },
      /**
       * 查询列表
       */
      onSearch() {
        var that = this;
        this.listLoading = true;
        if (this.formSearch.createtime) {
          this.formSearch.startdate = that.formartDate(this.formSearch.createtime[0]);
          this.formSearch.enddate = that.formartDate(this.formSearch.createtime[1]);
        } else {
          this.formSearch.startdate = '';
          this.formSearch.enddate = '';
        }
        let param = Object.assign({}, this.formSearch, this.pageInfo);
        apis.taskApi.getTaskPageList(param)
          .then((data) => {
            this.listLoading = false;
            if (data && data.data) {
              var json = data.data;
              if (json.successed) {
                if(json.data.list!=null&&json.data.list.length>0) {
                  console.log(json);
                  that.pageInfo.pageTotal = json.data.total;
                  that.pageInfo.currentPage = json.data.pageNum;
                  that.tableData = json.data.list;
                  that.tableData.forEach(ele => {
                    if (ele.status == 0)
                      ele.status = '未开始';
                    else if (ele.status == 1)
                      ele.status = '运行中';
                    else if (ele.status == 2)
                      ele.status = '暂停';
                    else if (ele.status == 3)
                      ele.status = '完成';
                  });
                }else{
                  that.tableData = [];
                }
              } else if (json.message) {
                this.$message({message: json.message, type: "error"});
              }
            }
          })
          .catch((err) => {
            this.listLoading = false;
            this.$message({message: '查询异常，请重试', type: "error"});
          });
      },
      handleSave() {
        if (this.dialogType == 'add') {
          this.save();
        } else if (this.dialogType == 'edit') {
          this.update();
        } else {
          this.$message({message: '操作异常', type: "error"});
        }
      },
      /**
       * 保存
       */
      save() {
        var that = this;
        this.$refs["formEdit"].validate(valid => {
          if (valid) {
            let param = Object.assign({}, this.formEdit);
            apis.taskApi.addTask(param)
              .then((data) => {
                if (data && data.data) {
                  var json = data.data;
                  if (json && json.successed) {
                    this.$message({message: '执行成功', type: "success"});
                    this.dialogEdittVisible = false;
                    that.onSearch();
                    return;
                  }
                }
                this.$message({message: data.data.message, type: "error"});
              })
              .catch((err) => {
                this.$message({message: '执行失败，请重试', type: "error"});
              });
          }


        });
      },
      /**
       * 更新
       */
      update() {
        var that = this;
        this.$refs["formEdit"].validate(valid => {
          if (valid) {
            let param = Object.assign({}, this.formEdit);
            apis.taskApi.updateTask(param)
              .then((data) => {
                console.log(data);
                if (data && data.data) {
                  var json = data.data;
                  if (json.successed) {
                    this.$message({message: '执行成功', type: "success"});
                    this.dialogEdittVisible = false;
                    that.onSearch();
                    return;
                  }
                }
                this.$message({message: '执行失败，请重试', type: "error"});
              })
              .catch((err) => {
                this.$message({message: '执行失败，请重试', type: "error"});
              });
          }


        });
      },
      /**
       * 删除
       */
      handleDelete(index, rowData) {
        console.log(this);
        var that = this;
        if (rowData.name == '使用文档') {
          this.$message('使用文档不可删除');
          return;
        }
        var taskId = rowData.taskId;
        this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = Object.assign({}, this.formEdit);
          apis.taskApi.deleteTask({taskId: taskId})
            .then((data) => {
              if (data.data.successed) {
                that.onSearch();
              }
              this.$common.isSuccess(data, () => {
                console.log("执行了");
              });
            })
            .catch((err) => {
              debugger;
              this.$message({message: '执行失败，请重试', type: "error"});
            });

        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除'});
        });

      },
      /**
       * 批量删除
       */
      deleteMany() {
        var ids = this.multipleSelection.map(item => item.id);
        if (ids.length == 0) {
          this.$message({message: '请选择要删除的项', type: "warn"});
          return;
        }
        debugger;
        this.$confirm('此操作将批量永久删除文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apis.msgApi.deleteBatch({ids: ids})
            .then((data) => {
              this.$common.isSuccess(data, () => {
                debugger;
                this.onSearch();
              });
            })
            .catch((err) => {
              debugger;
              this.$message({message: '执行失败，请重试', type: "error"});
            });

        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除'});
        });

      },
      handleSeedList(index, rowData) {
        this.$router.push({
          path: 'seedlist',
          query: {
            taskId: rowData.taskId
          }
        })
      },
      handleFilter(index, rowData) {
        this.$router.push({
          path: 'filter',
          query: {
            taskId: rowData.taskId
          }
        })
      },
      onReset() {
        //this.$refs['formSearch'].resetFields();
        this.formSearch={ //表单查询
          name: '',
          status:'',
          createTime: ''
        }
      },
      /**
       * 打开添加弹窗
       */
      handleAdd() {
        this.dialogEdittVisible = true;
        this.$nextTick(() => {
          this.dialogType = 'add';
          this.formEditTitle = '新增';
          this.formEditDisabled = false;
        });


      },
      /**
       * 打开编辑弹窗
       */
      handleEdit(index, rowData) {
        //var msg = "索引是:" + index + ",行内容是:" + JSON.stringify(rowData);
        //this.$message({message: msg,type: "success"});
        this.dialogEdittVisible = true;//等dom渲染完，读取data中初始值，然后再复制，这样重置的是data中初始值
        this.$nextTick(() => {
          this.dialogType = 'edit';
          this.formEditTitle = '编辑';
          this.formEditDisabled = false;
          this.formEdit = Object.assign({}, rowData);
          this.formEdit.gender += '';//必须转换成字符串才能回显
        });
      },
      /**
       * 打开详情页
       */
      handleDetail(index, rowData) {
        this.dialogEdittVisible = true;
        this.$nextTick(() => {
          this.dialogType = 'show';
          this.formEditTitle = '详情';
          this.formEditDisabled = true;
          this.formEdit = Object.assign({}, rowData);
          this.formEdit.gender += '';
        });

      },
      /**
       * 关闭弹框，数据重置
       */
      closeDialog(formName) {
        this.$refs[formName].resetFields();
      },
      handleTask(index, rowData) {
        this.$router.push({
          path: 'generatorlist',
          query: {
            taskId: rowData.taskId
          }
        })
      },
      handleParse(index, rowData) {
        this.$router.push({
          path: 'parse',
          query: {
            taskId: rowData.taskId
          }
        })
      },
      handleStart(index, rowData) {
        var that = this;
        apis.taskApi.startTask({taskId: rowData.taskId})
          .then((data) => {
            if (data.data.successed) {
              this.$message({message: '执行成功', type: "success"});
              that.onSearch();
              return;
            }
          })
          .catch((err) => {
            debugger;
            this.$message({message: '执行失败，请重试', type: "error"});
          });
      },
      handleStop(index, rowData) {
        var that = this;
        apis.taskApi.stopTask({taskId: rowData.taskId})
          .then((data) => {
            if (data.data.successed) {
              this.$message({message: '执行成功', type: "success"});
              that.onSearch();
              return;
            }
          })
          .catch((err) => {
            debugger;
            this.$message({message: '执行失败，请重试', type: "error"});
          });
      },
      /**
       * 分页大小切换
       */
      handleSizeChange(val) {
        this.pageInfo.pageSize = val;
        this.onSearch();
      },
      /**
       * 分页切换
       */
      handleCurrentChange(val) {
        this.pageInfo.currentPage = val;
        this.onSearch();
      },
      /**
       * 点击选择
       */
      handleSelectionChange(val) {
        this.multipleSelection = val;
        // this.$message({
        //     message: '选中的项是:' + JSON.stringify(this.multipleSelection),
        //     type: "success"
        // });
      },
      /**
       * 打开详情页
       */
      openDetail(row) {
        this.$common.OpenNewPage(this, 'detail', row);
      },
      handleStatus() {
        this.startStatus = true
      },
      /**
       *  时间对象转字符串
       */
      formartDate(time) {
        var that = this;
        var y = time.getFullYear();
        var m = time.getMonth() + 1;
        var d = time.getDate();
        //return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
        return y + that.add0(m) + that.add0(d);
      },
      add0(m) {
        return m < 10 ? '0' + m : m;
      }
    }
};
</script>
